package cn.edu.swu;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CourseDao {
    public void add(Course course) throws SQLException {
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "insert into course(CourseName,TeacherName) values(?,?)";
        queryRunner.update(sql,course.getCourseName(),course.getTeacherName());
    }
    public void delete(Integer id) throws SQLException{
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "delete from course where id=?";
        queryRunner.update(sql,id);
    }
    public void update(Course course) throws SQLException{
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "update course set CourseName=?,TeacherName=? where id =?";
        queryRunner.update(sql,course.getCourseName(),course.getTeacherName(),course.getId());
    }
    public List<Course> list(Course course) throws SQLException{
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from course";
        List<Course> list =queryRunner.query(sql,new BeanListHandler<>(Course.class));
        return list;
    }
    public Course findById(Integer id) throws SQLException {
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from course where id=?";
        Course course =queryRunner.query(sql,new BeanHandler<>(Course.class),id);
        return course;
    }
}
